/* 
 * Distributed as part of jdiff
 * 
 * Copyright (C) 2008 QArks.com
 *
 * Author: Pierre Meyer <support@qarks.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 2.1, as 
 * published by the Free Software Foundation.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; see the file LICENSE.  If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */
package diff.tela;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JTextField;

import com.qarks.util.ui.swing.FileChooserUtilities;

public class BrowseButton extends JButton {

	private JTextField pathField;
	private String defaultPath;
	private BrowseListener browseListener;

	public BrowseButton(JTextField pathField, String defaultPath,
			BrowseListener browseListener) {
		super("...");
		this.pathField = pathField;
		this.defaultPath = defaultPath;
		this.browseListener = browseListener;
		super.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				onBrowse();
			}
		});
	}

	public void setCurrentPath(String path) {
		defaultPath = path;
	}

	private void onBrowse() {
		File currentDirectory = null;
		if (defaultPath != null) {
			currentDirectory = new File(defaultPath);
		}
		File selectedFile = FileChooserUtilities.selectFile(this,
				"Select file", false, currentDirectory, null);
		if (selectedFile != null) {
			try {
				String path = selectedFile.getCanonicalPath();
				pathField.setText(path);
				if (browseListener != null) {
					browseListener.onBrowsed(path);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

}
